import { prisma } from '@/lib/prisma/client'
import { NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '../auth/[...nextauth]/route'

export async function POST(request: Request) {
  try {
    // 获取当前登录用户的 session
    const session = await getServerSession(authOptions)
    
    if (!session?.user?.id) {
      return NextResponse.json(
        { error: '未登录或登录已过期' },
        { status: 401 }
      )
    }

    const data = await request.json()

    const scene = await prisma.scene.create({
      data: {
        name: data.name,
        isActive: true,
        // 关联到当前登录用户
        userId: session.user.id,
        groupId: data.groupId || null,
        // 如果有设备关联
        devices: {
          connect: data.deviceIds?.map((id: string) => ({ id })) || []
        },
        // 如果有标签关联
        tags: {
          connect: data.tagIds?.map((id: string) => ({ id })) || []
        },
        // 创建条件
        conditions: {
          create: data.conditions?.map((condition: any) => ({
            type: condition.type,
            value: JSON.stringify(condition.value),
            operator: condition.operator || '=',
            deviceId: condition.deviceId
          })) || []
        },
        // 创建动作
        actions: {
          create: data.actions?.map((action: any) => ({
            type: action.type,
            value: JSON.stringify(action.value),
            deviceId: action.deviceId
          })) || []
        }
      },
      // 确保返回包含关联数据
      include: {
        conditions: true,
        actions: true,
        devices: true,
        group: true,
        tags: true,
        user: true
      }
    })

    return NextResponse.json(scene)
  } catch (error) {
    console.error('创建场景失败:', error)
    return NextResponse.json(
      { error: '创建场景失败' },
      { status: 500 }
    )
  }
}

export async function GET() {
  try {
    // 首先获取所有设备
    const devices = await prisma.device.findMany()
    
    // 然后获取场景
    const scenes = await prisma.scene.findMany({
      include: {
        conditions: true,
        actions: true,
        group: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
    })

    // 为每个场景的动作关联设备信息
    const scenesWithDevices = scenes.map(scene => {
      const sceneDevices = scene.actions
        .map(action => devices.find(d => d.id === action.deviceId))
        .filter(Boolean) // 移除 undefined

      return {
        ...scene,
        devices: sceneDevices
      }
    })
    
    return Response.json(scenesWithDevices)
  } catch (error) {
    console.error('Failed to fetch scenes:', error)
    return Response.json({ error: 'Failed to fetch scenes' }, { status: 500 })
  }
} 